package com.mySchool.controller;

import io.swagger.v3.oas.annotations.*;
import io.swagger.v3.oas.annotations.responses.*;
import io.swagger.v3.oas.annotations.tags.*;
import jakarta.annotation.*;
import jakarta.servlet.http.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.mail.*;
import org.springframework.mail.javamail.*;
import org.springframework.stereotype.*;
import org.springframework.validation.annotation.*;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
* @author : Hinton
* @时间 : 2024/11/10 下午4:24
*/
@RestController
@RequestMapping("/login")
@Validated
@Tag(name = "账户", description = "注册和登录")
public class RegisterController {

    @Autowired
    JavaMailSender sender;

    @Operation(summary = "设置验证码", description = "设置验证码")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "测试成功"),
            @ApiResponse(responseCode = "500", description = "测试失败")   //不同返回状态码描述
    })
    @GetMapping("/code")
    public String getCode(@Parameter(description = "邮箱", example = "1256202788@qq.com") @RequestParam String email ,
                          HttpSession session) {
        Random random = new Random();
        int code = random.nextInt(999999);
        session.setAttribute("code", code);
        session.setAttribute("email", email);
        SimpleMailMessage message = new SimpleMailMessage();

        //设置邮件标题
        message.setSubject("springboot验证码");
        //设置邮件内容
        message.setText("验证码: " + code);
        //设置邮件发送给谁，可以多个，这里就发给你的QQ邮箱
        message.setTo(email);
        //邮件发送者，这里要与配置文件中的保持一致
        message.setFrom("17816139241@163.com");
        // 发送
        sender.send(message);

        return "发送成功";
    }

    @PostMapping("/register")
    public String register(@RequestParam String username,
                           @RequestParam String email,
                           @RequestParam String code,
                           HttpSession session) {
        String sessionCode = (String) session.getAttribute("code").toString();
        String sessionEmail = (String) session.getAttribute("email").toString();
        if (sessionCode == null) {
            return "请先获取验证码";
        }
        if (!sessionCode.equals(code)) {
            return "验证码错误";
        }
        if (!email.equals(sessionEmail)) {
            return "请先获取验证码";
        }

        return "注册成功";
    }
}
